package io.mft.commons.ioc;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;



public class SpringIocRegistryScanner extends ClassPathScanningCandidateComponentProvider {
	private String basePackage;
	private String sysNo;
	
	private static final Logger logger = LoggerFactory.getLogger(SpringIocRegistryScanner.class);

	public SpringIocRegistryScanner(String sysNo,String basePackage) {
		super(false);
		addIncludeFilter(new AnnotationTypeFilter(SpringIocRegistry.class));
		this.basePackage=basePackage;
		this.sysNo=sysNo;
	}

	@Override
	protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
		return beanDefinition.getMetadata().isConcrete();
	}
	public void scanAndRegistry(BeanDefinitionRegistry registry,List<MFTBasePackage> registryBasePackages){
		Set<BeanDefinition> beanDefinitions=findCandidateComponents(basePackage);
		for (BeanDefinition definition : beanDefinitions) {
			try {
				String beanClassName=definition.getBeanClassName();
				Class<?> classType=Class.forName(beanClassName);
				for (MFTBasePackage basePackage : registryBasePackages) {
					try {
						Constructor<?> constructor=classType.getConstructor(String.class,String.class);
						Registry obj=(Registry)constructor.newInstance(basePackage.getSysNo(),basePackage.getBasePackage());
						obj.reg(registry);
					} catch (Exception e) {
						logger.error("",e);
					}

				}
			} catch (Exception e) {
				logger.error("",e);
			}
		}
	}
}
